<?php
/**
 * Class 登录.
 * User: chan
 * Date: 2017/10/26 15:29
 */

namespace app\pc\controller;
use app\pc\model\Member as memberModel;
class Login extends Base
{
    //检查权限作用域
    protected $beforeActionList  = [
        'checkPrimaryScope' => [
            'only' => 'updateuserinfo'
        ],
    ];

    public function login()
    {
       $login =  (new \app\pc\logic\Login())->login();
       return $this->ajaxReturn($login);
    }

    public function registered()
    {
       $registered =  (new \app\pc\logic\Login())->registered();
       return $this->ajaxReturn($registered);
    }

    public function wxlogin()
    {
        (new \app\api\validate\Login())->checkWxLoginParam();
        //使用登录凭证 code 获取会话密钥session_key和唯一标识openid。用户数据的加解密通讯需要依赖会话密钥完成。
        $uri = sprintf(config('wx.uri'),config('wx.app_id'),config('wx.app_secret'),$this->requestData['js_code']);
        $data =  json_decode(file_get_contents($uri),true);

        if(empty($data['session_key']) && empty($data['openid'])) return $this->ajaxReturn(['message'=>'请求失败']);

        $Oauth2 =  new \app\api\service\Oauth2();
        $original['original'] = [
            'session_key'=>$data['session_key'],
            'wx_openid'=>$data['openid']
        ];

        $userInfo = (new memberModel())->getUser($original);
        
        if (array_key_exists('message',$userInfo) && $userInfo['type'] == 'create') return $this->ajaxReturn($userInfo);
        
        $token =  $Oauth2::generateToken($userInfo['user']);

        return $this->ajaxReturn($token);
    }

    public function updateuserinfo()
    {   
        $data = $this->checkParameters($this->requestData);
        $user = (new memberModel())->updateUser($this->user['id'],$data);
        return $this->ajaxReturn($user);
    }

    //验证码
    public function captchaImg(){
        $captchaImg = (new \app\pc\logic\Login())->captchaImg();
        return $this->ajaxReturn($captchaImg);
    }
}